package controller.ur.note;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;

import model.dao.NoteDaoLocal;
import model.dao.PhotoDaoLocal;
import model.entity.Note;
import model.entity.Photo;

/**
 * Servlet implementation class SNoteSave
 */
public class SNoteSave extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB
	private PhotoDaoLocal photoDao;
	
	@EJB
	private NoteDaoLocal noteDao;
	
	private Logger log=Logger.getLogger(SNoteSave.class);
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SNoteSave() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pids=(String)request.getParameter("photoId");
		String top=(String)request.getParameter("top");
		String left=(String)request.getParameter("left");
		String width=(String)request.getParameter("width");
		String height=(String)request.getParameter("height");
		String text=(String)request.getParameter("text");
		String noteId=(String)request.getParameter("id");
		Photo photo=photoDao.findById(Integer.parseInt(pids));
		Note note=null;
		if(photo!=null){
			if(noteId.equals("new")){
				note=new Note();
				note.setCaption(text);
				note.setX(Integer.parseInt(top));
				note.setY(Integer.parseInt(left));
				note.setWidth(Integer.parseInt(width));
				note.setHeight(Integer.parseInt(height));
				
				note.setPhoto(photo);
				noteDao.persist(note);
			}else{
				note=noteDao.findById(Integer.parseInt(noteId));
				if(note!=null){
					note.setCaption(text);
					note.setX(Integer.parseInt(top));
					note.setY(Integer.parseInt(left));
					note.setWidth(Integer.parseInt(width));
					note.setHeight(Integer.parseInt(height));
	
					noteDao.merge(note);
				}
			}
		}
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		Map<String, String> options;

		options = new LinkedHashMap<String, String>();
	    options.put("annotation_id", note.getId().toString());
	    String json = new Gson().toJson(options);
	    response.getWriter().write(json);
	    response.getWriter().close();
	    log.info("Note modified: "+note.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

}
